package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bean.DBConfigure;
import bean.DevDBConfigure;
import bean.LoggedUser;
import bean.Model;
import bean.UserType;


public class Controller extends HttpServlet {
    public void init() throws ServletException {
    	DBConfigure dbConfigure = new DevDBConfigure();//Change to cloud one when deploying to CloudFoundry
    	Model model = new Model(dbConfigure);
    	Action.add(new LoginAction(model));
    	Action.add(new ModifyCustomerPasswordAction(model));
    	Action.add(new CreateFundAction(model));
    	Action.add(new TransactionHistoryAction(model));
    	Action.add(new CreateEmployeeAccAction(model));
    	Action.add(new ViewCustomerAction(model));
    	Action.add(new CreateCustomerAction(model));
    	Action.add(new ChangePasswordAction(model));
    	Action.add(new DepositCheckAction(model));
    	
    	//Added by Sahil
    	Action.add(new BuyFundAction(model));
    	Action.add(new OpenBuyFundAction(model));
    	Action.add(new ResearchFundAction(model));
    	Action.add(new ViewPortfolioAction(model));
    	Action.add(new SellFundAction(model));
    	Action.add(new OpenSellFundAction(model));
    	Action.add(new OpenRequestCheckAction(model));
    	Action.add(new RequestCheckAction(model));
    	Action.add(new OpenResearchFundAction(model));
    	
    	Action.add(new TransitionDayAction(model));
    	Action.add(new LogoutAction());
    	Action.add(new ViewAccountAction(model));

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nextPage = performTheAction(request);
        sendToNextPage(nextPage,request,response);
    }
    
    /*
     * Extracts the requested action and (depending on whether the user is logged in)
     * perform it (or make the user login).
     * @param request
     * @return the next page (the view)
     */
    private String performTheAction(HttpServletRequest request) {
        HttpSession session     = request.getSession(true);
        String      servletPath = request.getServletPath();
        LoggedUser user = (LoggedUser) session.getAttribute("user");
        String action = getActionName(servletPath);
        
        if (user == null) {
        	// If the user hasn't logged in, direct him to the login page
			return Action.perform("login.do",request);
        }
        
        if (!checkType(action, user)) {
        	request.setAttribute("message", "Sorry, you are not authorized to do that.");
        	return "employeeConsole.jsp";
        }
        
      	// Let the logged in user run his chosen action
		return Action.perform(action,request);
    }
    
    /*
     * If nextPage is null, send back 404
     * If nextPage starts with a '/', redirect to this page.
     *    In this case, the page must be the whole servlet path including the webapp name
     * Otherwise dispatch to the page (the view)
     *    This is the common case
     * Note: If nextPage equals "image", we will dispatch to /image.  In the web.xml file, "/image"
     *    is mapped to the ImageServlet will which return the image bytes for display.
     */
    private void sendToNextPage(String nextPage, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    	// System.out.println("nextPage="+nextPage);
    	
    	if (nextPage == null) {
    		response.sendError(HttpServletResponse.SC_NOT_FOUND,request.getServletPath());
    		return;
    	}
    	
    	if (nextPage.charAt(0) == '/') {
			String host  = request.getServerName();
			String port  = ":"+String.valueOf(request.getServerPort());
			if (port.equals(":80")) port = "";
			response.sendRedirect("http://"+host+port+nextPage);
			return;
    	}
    	
   		RequestDispatcher d = request.getRequestDispatcher("/"+nextPage);
   		d.forward(request,response);
    }

	/*
	 * Returns the path component after the last slash removing any "extension"
	 * if present.
	 */
    private String getActionName(String path) {
    	// We're guaranteed that the path will start with a slash
        int slash = path.lastIndexOf('/');
        return path.substring(slash+1);
    }

    private boolean checkType(String name, LoggedUser user) {
    	Action action = Action.getAction(name);
    	if(action.getType().equals(UserType.Both)) return true;
    	else return action.getType().equals(user.getUserType());
    }
}
